package com.zhyonk.service.impl;

import com.zhyonk.config.propreties.HtmlToPdf;
import com.zhyonk.service.GenNoticeService;
import com.zhyonk.util.BaseUtils;
import com.zhyonk.util.FilesUtils;
import com.zhyonk.util.OsInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Component
public class GenNoticeServiceImpl implements GenNoticeService {

    @Autowired
    private HtmlToPdf HtmlToPdf;

    @Override
    public String fillDataToHtml(String userId, String templateFilePath, List<String> data) throws IOException {
        StringBuilder stringBuilder = new StringBuilder();
        File temFile = new File(templateFilePath);
        if (!temFile.exists()) {
            throw new IOException();
        }
        BufferedReader br = Files.newBufferedReader(Paths.get(templateFilePath));
        List<String> list = br.lines().collect(Collectors.toList());
        if (list.isEmpty()) {
            throw new IOException();
        }
        int i = 0;
        for (String str : list) {
            if (str.indexOf("$DATA$") > 0) {
                str = str.replace("$DATA$", data.get(i++));
            }
            stringBuilder.append(str).append("\n");
        }
        String writerStr = new String(stringBuilder.toString().getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
        String htmlOutPath = OsInfo.isWindows() ? HtmlToPdf.getWindowsOutputHtmlPath() +
                BaseUtils.getDateStr("yyyyMMdd") + "/cert_" + userId + ".html" :
                HtmlToPdf.getLinuxOutputHtmlPath() + BaseUtils.getDateStr("yyyyMMdd") +
                        "/cert_" + userId + ".html";
        FilesUtils.checkFolderAndCreate(Objects.requireNonNull(htmlOutPath));
        Files.write(Paths.get(Objects.requireNonNull(htmlOutPath)), writerStr.getBytes());
        return htmlOutPath;
    }

}
